package it.trekker.dao.ejb;

import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.security.annotation.SecurityDomain;

import it.trekker.dao.Excursion;
import it.trekker.dao.ExcursionCoordinate;
import it.trekker.dao.IExcursionCoordinateDAO;

@SecurityDomain("TrekkerRealm")
@RolesAllowed("viewer")
@Stateless
@Local(IExcursionCoordinateDAO.class)
public class EJB3ExcursionCoordinateDAO implements IExcursionCoordinateDAO {

	@PersistenceContext(unitName = "TrekkerUnit")
	protected EntityManager em;

	public int insert(ExcursionCoordinate coordinate) {
		if(coordinate != null) {
			if(coordinate.getExcursion() != null && coordinate.getExcursion().getId() > 0)
				coordinate.setExcursion(em.merge(coordinate.getExcursion()));
			
			em.persist(coordinate);
			return coordinate.getId();
		}

		return 0;
	}

	public int remove(int id) {
		ExcursionCoordinate coordinate = findCoordinateById(id);
		
		if(coordinate != null) {
			em.remove(coordinate);
			return id;
		}
		
		return 0;
	}

	public int update(ExcursionCoordinate coordinate) {
		if(coordinate != null) {
			if(em.merge(coordinate) != null)
				return coordinate.getId();
		}
		
		return 0;
	}

	public ExcursionCoordinate findCoordinateById(int id) {
		return em.find(ExcursionCoordinate.class, id);
	}

	public List<ExcursionCoordinate> findCoordinateByExcursion(Excursion excursion) {
		if(excursion != null) {
			excursion = em.merge(excursion);
			
			return 	em.createQuery(
						"SELECT DISTINCT (c) " +
						"FROM ExcursionCoordinate c JOIN FETCH c.excursion " +
						"WHERE c.excursion = :excursion "
//						"ORDER BY c.timestamp"
					).setParameter("excursion", excursion).getResultList();
		}
		
		return null;
	}

	public List<ExcursionCoordinate> findAllCoordinates() {
		return em.createQuery("from ExcursionCoordinate c").getResultList();
	}
	
	
}
